package routers

import (
	"server/global"
	"server/internal/service"
	"server/pkg/app"
	"server/pkg/errcode"

	"github.com/gin-gonic/gin"
)

type UserInfo struct{}

func NewUserInfo() *UserInfo {
	return &UserInfo{}
}

func (u *UserInfo) GetUserInfo(c *gin.Context) {
	param := &struct {
		Username string `form:"username" binding:"required"`
	}{}
	response := app.NewResponse(c)
	valid, errs := app.BindAndValid(c, param)
	if !valid {
		global.Logger.Errorf("app.BindAndValid errs: %v", errs)
		errRsp := errcode.InvalidParams.WithDetails(errs.Errors()...)
		response.ToErrorResponse(errRsp)
		return
	}

	svc := service.New(c.Request.Context())
	userInfo, err := svc.GetUserInfo(param.Username)
	if err != nil {
		response.ToErrorResponse(errcode.ErrorGetUserInfoFail)
		return
	}

	response.ToSuccessResponse(userInfo)
}

func (u *UserInfo) SetUserInfo(c *gin.Context) {
	param := &struct {
		Username    string `form:"username" binding:"required"`
		SchoolId    string `form:"schoolId" binding:"required"`
		Name        string `form:"name" binding:"required"`
		IsMale      int    `form:"isMale" binding:"required"`
		PhoneNumber string `form:"phoneNumber" binding:"required"`
	}{}
	response := app.NewResponse(c)
	valid, errs := app.BindAndValid(c, param)
	if !valid {
		global.Logger.Errorf("app.BindAndValid errs: %v", errs)
		errRsp := errcode.InvalidParams.WithDetails(errs.Errors()...)
		response.ToErrorResponse(errRsp)
		return
	}

	svc := service.New(c.Request.Context())
	err := svc.SetUserInfo(param.Username, param.SchoolId,
		param.Name, param.PhoneNumber, param.IsMale)
	if err != nil {
		response.ToErrorResponse(errcode.ErrorSetUserInfoFail)
		return
	}

	response.ToSuccessResponse(nil)
}
